const mysql = require('../../core/mysql');

const log = require('../../core/logger').getLogger("system");
const moment = require('moment');
const common = require('../../core/common');
const stringUtils = require('../../core/util/StringUtils');
const assign = require("lodash/assign");
const keys = require("lodash/keys");
const values = require("lodash/values");

function insertScenario(ctx,scenario_name,icon_id,room_id, house_type_id, hashScenarioMap){
    return new Promise((resolve, reject) => {
        let newscenario = {
            scenario_name,
            icon_id,
            room_id,
            house_type_id,
            is_deleted: 0,
            create_time: moment().format('YYYY-MM-DD HH:mm:ss'),
            update_time: moment().format('YYYY-MM-DD HH:mm:ss'),
        };

        var trans = mysql.Client.startTransaction();
        trans.query(`INSERT INTO scenario SET ?`, newscenario, function(err, info) {
            if(err){
                trans.rollback();
                ctx.body = {
                    result: 202,
                    message: "新增楼幢失败"+ err.toString()
                };
                resolve(ctx);
            } else{
                let sqlInsertScenario_V_Device = `INSERT INTO t_scenario_v_device (scenario_id,v_device_id,property_values,type) VALUES  `;
                hashScenarioMap.forEach(ele => {

                    sqlInsertScenario_V_Device += `(${info.insertId }, ${ele.v_device_id}, '${ele.property_values}', "${ele.type}" ),`;
                })
                sqlInsertScenario_V_Device = sqlInsertScenario_V_Device.substr(0,sqlInsertScenario_V_Device.length-1);
                trans.query(sqlInsertScenario_V_Device, function(err) {
                    if(err){
                        trans.rollback();
                        ctx.body = {
                            result: 209,
                            message: "新增场景失败"+ err.toString()
                        };
                    } else{
                        trans.commit();
                        ctx.body = {
                            result: 200,
                            id: info.insertId,
                            message: "新增场景成功"
                        };
                    }
                    resolve(ctx);
                });
            }
        });
        trans.execute();
    });
};

function updateScenario(ctx,scenario_id, scenario_name,icon_id,room_id, house_type_id, hashScenarioMap){
    return new Promise((resolve, reject) => {
        let newscenario = {
            scenario_id,
            scenario_name,
            icon_id,
            room_id,
            house_type_id,
            is_deleted: 0,
            create_time: moment().format('YYYY-MM-DD HH:mm:ss'),
            update_time: moment().format('YYYY-MM-DD HH:mm:ss'),
        };

        var trans = mysql.Client.startTransaction();
        trans.query(`UPDATE scenario SET ? where scenario_id = ${scenario_id}`, newscenario, function(err, info) {
            if(err){
                trans.rollback();
                ctx.body = {
                    result: 202,
                    message: "更新场景失败"+ err.toString()
                };
                resolve(ctx);
            } else{
                let sqlInsertScenario_V_Device =  `UPDATE t_scenario_v_device SET property_values = CASE v_device_id `;
                hashScenarioMap.forEach(ele => {
                    sqlInsertScenario_V_Device+= `WHEN ${ele.v_device_id} THEN '${ele.property_values}' `;
                })
                sqlInsertScenario_V_Device+= `END WHERE scenario_id =${scenario_id} `
                trans.query(sqlInsertScenario_V_Device, function(err) {
                    if(err){
                        trans.rollback();
                        ctx.body = {
                            result: 209,
                            message: "更新场景失败"+ err.toString()
                        };
                    } else{
                        trans.commit();
                        ctx.body = {
                            result: 200,
                            id: info.insertId,
                            message: "更新场景成功"
                        };
                    }
                    resolve(ctx);
                });
            }
        });
        trans.execute();
    });
};


exports.add = async(ctx) => {
    let scenario_name = ctx.request.body.scenario_name || '';
    let icon_id = ctx.request.body.icon_id || '';
    let matching_condition = JSON.parse(ctx.request.body.matching_condition) || [];
    let triggering_condition = JSON.parse(ctx.request.body.triggering_condition) || [];
    let action = JSON.parse(ctx.request.body.action) || [];
    let house_type_id = ctx.request.body.house_type_id || '';
    let room_id = ctx.request.body.room_id || 0;



    if (scenario_name === '' || house_type_id === '') {
        ctx.body = {
            result: 201,
            message: "请检查参数"
        };
        return;
    }
    try{
        let hashScenarioMap = [];

        if (triggering_condition.length > 0) {
            triggering_condition.forEach((ele, index) => {
                let obj2 = {v_device_id:  keys(ele)[0], property_values: values(ele)[0], type: 0}
                hashScenarioMap.push(obj2);
                console.log(JSON.stringify(hashScenarioMap))
            })
        }
        if (matching_condition.length > 0) {
            matching_condition.forEach((ele, index) => {
                let obj = {v_device_id:  keys(ele)[0], property_values: values(ele)[0], type: 1 }
                hashScenarioMap.push(obj);
            })

        }
        if (action.length > 0) {
            action.forEach((ele, index) => {
                let obj3 = {v_device_id:  keys(ele)[0], property_values: values(ele)[0], type: 2 }
                hashScenarioMap.push(obj3);
            })

        }

        await insertScenario(ctx,scenario_name,icon_id,room_id, house_type_id,hashScenarioMap);

        // ret = mysql.Client.query('SELECT * FROM building');
        // console.log('ret:',ret)
    }catch (e) {
        ctx.body = {
            result: 205,
            message: "新增场景失败"+e.toString()
        };
    }

}

exports.delete = async(ctx) => {
    let scenario_id = ctx.params.scenario_id || 0;
    if (scenario_id <= 0) {
        ctx.body = {
            result: 201,
            message: "请检查参数"
        };
        return
    }
    try{
        ret = await mysql.query(`UPDATE scenario SET is_delete = ？ WHERE scenario_id = ${scenario_id}`, 1);
        ctx.body = {
            result: 200,
            message: "删除成功"
        }
    }catch (e) {
        ctx.body = {
            result: 203,
            message: "删除失败"+e.toString()
        };
    }
}

exports.update = async(ctx) => {
    let scenario_id = ctx.request.body.scenario_id;
    let scenario_name = ctx.request.body.scenario_name || '';
    let icon_id = ctx.request.body.icon_id || '';
    let matching_condition = JSON.parse(ctx.request.body.matching_condition) || [];
    let triggering_condition = JSON.parse(ctx.request.body.triggering_condition) || [];
    let action = JSON.parse(ctx.request.body.action) || [];
    let house_type_id = ctx.request.body.house_type_id || '';
    let room_id = ctx.request.body.room_id || 0;



    if (!scenario_id) {
        ctx.body = {
            result: 201,
            message: "请检查参数"
        };
        return;
    }
    try{
        let hashScenarioMap = [];

        if (triggering_condition.length > 0) {
            triggering_condition.forEach((ele, index) => {
                let obj2 = {v_device_id:  keys(ele)[0], property_values: values(ele)[0], type: 0}
                hashScenarioMap.push(obj2);
                console.log(JSON.stringify(hashScenarioMap))
            })
        }
        if (matching_condition.length > 0) {
            matching_condition.forEach((ele, index) => {
                let obj = {v_device_id:  keys(ele)[0], property_values: values(ele)[0], type: 1 }
                hashScenarioMap.push(obj);
            })

        }
        if (action.length > 0) {
            action.forEach((ele, index) => {
                let obj3 = {v_device_id:  keys(ele)[0], property_values: values(ele)[0], type: 2 }
                hashScenarioMap.push(obj3);
            })

        }

        await updateScenario(ctx,scenario_id,scenario_name,icon_id,room_id, house_type_id,hashScenarioMap);

        // ret = mysql.Client.query('SELECT * FROM building');
        // console.log('ret:',ret)
    }catch (e) {
        ctx.body = {
            result: 205,
            message: "更新场景失败"+e.toString()
        };
    }

}


exports.getList = async(ctx) => {
    let create_user_id = ctx.user.id || '';
    let counts = ctx.query.counts || 10;
    let indexfrom = ctx.query.indexfrom || 0;
    let scenario_type = ctx.query.scenario_type;
    let house_type_id = ctx.query.house_type_id;


    if (create_user_id === ''){
        ctx.body = {
            result: 201,
            message: "无效的用户id"
        };
    } else {
        try {
            let results;
            if(scenario_type && !house_type_id) {
                results = await mysql.query(`SELECT * FROM scenario WHERE scenario_type = ${scenario_type} ORDER BY scenario_id LIMIT ${indexfrom}, ${counts}  ` );
            }
            else if (!scenario_type && house_type_id) {
                results = await mysql.query(`SELECT * FROM scenario WHERE house_type_id = ${house_type_id} ORDER BY scenario_id LIMIT ${indexfrom}, ${counts}  ` );
            } else if (scenario_type && house_type_id) {
                results = await mysql.query(`SELECT * FROM scenario WHERE house_type_id = ${house_type_id} and scenario_type = ${scenario_type} ORDER BY scenario_id LIMIT ${indexfrom}, ${counts}  ` );
            } else {
                results = await mysql.query(`SELECT * FROM scenario ORDER BY scenario_id LIMIT ${indexfrom}, ${counts}  ` )
                for (let i of values(results)){
                    i.deviceActions = await mysql.query(`SELECT * FROM t_scenario_v_device where scenario_id = ${i.scenario_id} ` );

                }
            }

            ctx.body = {
                result: 200,
                list:results,
                message: "查询成功"
            };
        }catch (e) {
            ctx.body = {
                result: 205,
                message: "数据库错误"+e.toString()
            };
        }
    }
}